import React from 'react';
import _ from 'lodash';
import { Input } from 'antd';
import { useTablePipeline, features } from 'ali-react-table';

import { EditOutlined } from '#/utils/antdIcons.js';
import { TjTable } from '@/pages/ETrade/components/index.js';

import { canEditorList } from '../../helper.js';
import styles from './index.less';

export default ({ props, onSave }: any) => {
  const { tableData, tableHead } = props;

  const [openKeys, onChangeOpenKeys]: any = React.useState([1]);
  const [editor, setEditor] = React.useState<any>(null);
  const [editName, setEditName] = React.useState();

  // 处理表头
  const getColumns = (columsValue: any[]) => {
    const columns: any[] = [];
    // 添加表格第一列标题
    columns.push({
      name: '交易单元',
      align: 'left',
      code: 'name',
      width: 120,
      lock: true,
    });

    const parentNames: any[] = Object.keys(_.groupBy(columsValue, 'parentName'));
    parentNames.map((item: string) => {
      columns.push({
        name: item,
        align: 'center',
        children: [],
      });
    });

    columns.map((colItem: any, index: number) => {
      const children: any[] = [];
      columsValue.map((item: any) => {
        if (colItem.name == item.parentName) {
          const isEdit = canEditorList.find((t: any) => item.name.includes(t));
          children.push({
            name: item.name,
            align: 'center',
            width: isEdit ? 130 : 100,
            code: item.field,
            render: (value: any, record: any) => {
              if (isEdit && !record.flag.includes('合计') && !record.flag.includes('parent')) {
                return editor?.id === record.id && item.field === editName ? (
                  <div>
                    <Input
                      onChange={(e) => {
                        setEditor({ ...editor, [item.field]: e.target.value });
                      }}
                      defaultValue={editor?.[item.field]}
                      className={styles.inputBox}
                    />
                    <a
                      onClick={() => {
                        onSave(editor);
                      }}
                      className={styles.btn}
                    >
                      保存
                    </a>
                    <a
                      onClick={() => {
                        setEditor(null);
                      }}
                      className={styles.btn}
                    >
                      取消
                    </a>
                  </div>
                ) : (
                  <>
                    {value || '-'}
                    <EditOutlined
                      onClick={() => {
                        setEditor(record);
                        setEditName(item.field);
                      }}
                      className={styles.edit}
                    />
                  </>
                );
              }
              return value || '-';
            },
          });
        }
      });
      columns[index].children = children;
    });
    return columns;
  };

  // 处理表格数据
  const getDataSource = (dataSource: any[]) => {
    const newDataSource: any[] = [];
    dataSource.map((item, index) => {
      item.id = index + 1;
      // eslint-disable-next-line no-param-reassign
      item = Object.assign(item, item.data);
      (item?.children || []).map((y: any, yIndex: number) => {
        y.id = `${index + 1}-${yIndex + 1}`;
        // eslint-disable-next-line no-param-reassign
        y = Object.assign(y, y.data);
        (y?.children || []).map((z: any, zIndex: number) => {
          // eslint-disable-next-line no-param-reassign
          z = Object.assign(z, z.data);
          z.id = `${index + 1}-${yIndex + 1}-${zIndex + 1}`;
        });
      });
      newDataSource.push(item);
    });

    return newDataSource;
  };

  const dataTable = _.cloneDeep(tableData);
  const [dataSource] = React.useState(getDataSource(dataTable));
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: dataSource, columns: getColumns(tableHead) })
    .primaryKey('id')
    .use(
      features.treeMode({
        openKeys,
        onChangeOpenKeys,
        indentSize: 20,
      }),
    );

  return (
    <TjTable
      style={{
        // '--header-bgcolor': '#434749',
        '--header-color': 'white',
        '--border-color': 'rgba(255, 255, 255, 0.1)',
        '--header-row-height': '36px',
        '--font-size': '12px',
        '--cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
        '--header-cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
        '--bgcolor': '#222629',
        '--color': 'white',
        '--hover-bgcolor': '#222629',
        '--cell-padding': '4px 5px',
        marginLeft: '24px',
        border: '1px solid #444',
        borderRadius: '5px',
      }}
      useOuterBorder={true}
      stickyScrollHeight={10}
      useVirtual={{ horizontal: true, vertical: true, header: false }}
      {...pipeline.getProps()}
    />
  );
};
